package com.xinxing.learning.security.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest()
                .authenticated()
                .and().formLogin()
                .and()
                // spring-security跨域结局方案配置
                .cors()
                // 第一种
                .configurationSource(corsConfigurationSource())
                // 第二种
                // .configurationSource(new CorsConfigurationSource() {
                //     @Override
                //     public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
                //         CorsConfiguration corsConfiguration = new CorsConfiguration();
                //         corsConfiguration.setAllowCredentials(false);
                //         corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
                //         corsConfiguration.setAllowedMethods(Arrays.asList("*"));
                //         corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
                //         corsConfiguration.setMaxAge(3600L);
                //
                //         return corsConfiguration;
                //     }
                // })
                .and().csrf().disable()
        ;
    }

    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(false);
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
        corsConfiguration.setAllowedMethods(Arrays.asList("*"));
        corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
        corsConfiguration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);

        return urlBasedCorsConfigurationSource;
    }
}
